package nccloud.web.tmpub.base.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nc.itf.uap.rbac.IUserManageQuery_C;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nc.vo.pub.filesystem.NCFileVO;
import nc.vo.sm.UserVO;
import nc.vo.tmpub.util.ArrayUtil;
import nc.vo.tmpub.util.ModuleEnum;
import nc.vo.tmpub.util.ModuleUtil;
import nc.vo.tmpub.util.StringUtil;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.core.json.IJson;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.container.SessionContext;
import nccloud.framework.web.json.JsonFactory;
import nccloud.itf.uap.pf.NCCWorkFlowService;
import nccloud.pubitf.platform.attachment.IAttachmentService;
import nccloud.pubitf.platform.attachment.IFileStorageConst;
import nccloud.pubitf.platform.attachment.WebFileParaVO;
import nccloud.web.platform.attachment.action.WebFileParaConvertor;








public class TmpubFileAttachmentQueryAction
  implements ICommonAction
{
  public Object doAction(IRequest request) {
    String str = request.read();
    
    String requestJson = request.getJson();
    IJson json = JsonFactory.create();
    WebFileParaVO para = json.fromJson(str, WebFileParaVO.class);
    if (para.getFullPath() == null || para.getFullPath().length() == 0)
    {
      ExceptionUtils.wrapBusinessException(
          NCLangRes4VoTransl.getNCLangRes().getStrByID("1501003_0", "01501003-0112"));
    }
    
    NCFileVO[] ncfiles = null;
    String newBucket = getStorePath(para);
    List<NCFileVO> ncList = new ArrayList<NCFileVO>();
    if ("riamsgattachfiles".equals(newBucket)) {

      
      NCCWorkFlowService wfService = ServiceLocator.find(NCCWorkFlowService.class);
      ncfiles = wfService.getAttacthByPkCheckFlow(para.getBillId());
      WebFileParaConvertor convertor = new WebFileParaConvertor();
      return convertor.convert(ncList
          .toArray(new NCFileVO[0]), para.getBillId(), newBucket);
    } 


    
    HashMap<String, String> filePathMap = new HashMap<String, String>();
    
    IAttachmentService ncservice = ServiceLocator.find(IAttachmentService.class);
    ncfiles = ncservice.queryNCFilesByNodePath(para.getFullPath(), 
        SessionContext.getInstance().getClientInfo().getUserid());
    ncList = new ArrayList<NCFileVO>(Arrays.asList(ncfiles));
    
    String foldname = NCLangRes4VoTransl.getNCLangRes().getStrByID("3601nccloud_ncc_0", "03601nccloud_ncc-0052");
    if ((para.getFullPath().equals(para.getBillId()) || para
      .getFullPath().contains(foldname)) && 
      !StringUtil.isNull(para.getBillId())) {
      try {
        String pk_group = SessionContext.getInstance().getClientInfo().getPk_group();
        
        boolean isOBMEnable = ModuleUtil.isEnableByGroup(pk_group, ModuleEnum.OBM);
        if (isOBMEnable) {
          String[] receiptIds = queryEbankEleReceipt(para
              .getBillId());
          
          if (!ArrayUtil.isNull(receiptIds)) {
            for (int i = 0; i < receiptIds.length; i++) {
              
              NCFileVO[] files = ncservice.queryNCFilesByNodePath(receiptIds[i], 
                  SessionContext.getInstance()
                  .getClientInfo()
                  .getUserid());
              Collections.addAll(ncList, files);
            } 
          }
        } 
        if (ModuleUtil.isEnableByGroup(pk_group, ModuleEnum.SP)) {
          NCFileVO[] bankReceiptFiles = queryBankReceiptFiles(para.getBillId());
          if (!ArrayUtil.isNull(bankReceiptFiles)) {
            for (NCFileVO file : bankReceiptFiles) {
              StringBuffer fullpath = new StringBuffer();
              int start = file.getFullPath().indexOf("/");
              String filename = file.getFullPath().substring(start);
              fullpath.append(para.getBillId()).append("/").append(foldname).append(filename);
              filePathMap.put(file.getPk(), fullpath.toString());
            } 
            ncList.addAll(Arrays.asList(bankReceiptFiles));
          } 
        } 
      } catch (BusinessException e) {
        ExceptionUtils.wrapException(e);
      } 
    }
    
    List<String> cibFileDocs = new ArrayList<String>();
    if (StringUtil.isNotNull(requestJson) && requestJson.contains("36180BS") && 
      !para.getFullPath().contains(foldname)) {
      
      try {
        NCFileVO[] signCIBFiles = querySignCIBFiles(para.getBillId());
        if (!ArrayUtil.isNull(signCIBFiles)) {
          for (NCFileVO ncFileVO : signCIBFiles) {
            cibFileDocs.add(ncFileVO.getPk_doc());
          }
          ncList.addAll(Arrays.asList(signCIBFiles));
        } 
      } catch (BusinessException e) {
        ExceptionUtils.wrapException(e);
      } 
    }
    
    if (ncfiles != null && ncfiles.length != 0) {
      IUserManageQuery_C iUserManageQuery_C = ServiceLocator.find(IUserManageQuery_C.class);
      String[] userIds = new String[ncfiles.length];
      int i = 0;
      for (NCFileVO ncvo : ncfiles) {
        userIds[i] = ncvo.getCreator();
        i++;
      } 
      UserVO[] userVOs = null;
      try {
        //userVOs = iUserManageQuery_C.findUserByIDs(userIds);
		List<UserVO> listuses = new ArrayList<UserVO>();
		UserVO[] findUserByIDs = iUserManageQuery_C.findUserByIDs(userIds);
		for(UserVO userVO :findUserByIDs) {
			if(userVO != null ) {
				listuses.add(userVO);
			}
		}
		userVOs = listuses.toArray(new UserVO[listuses.size()]);
      } catch (BusinessException e) {
        
        ExceptionUtils.wrapBusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("3601nccloud_ncc2_0", "03601nccloud_ncc2-0014"));
      } 
      Map<String, UserVO> map = new HashMap<String, UserVO>();

      
      if (!ArrayUtil.isNull(userVOs))
      {
        for (UserVO userVO : userVOs) {
		if(userVO != null) {
			map.put(userVO.getCuserid(), userVO);
		}
        }
      }
      if (map != null && !map.isEmpty()) {
        for (NCFileVO ncvo : ncfiles) {
        	UserVO userVO = map.get(ncvo.getCreator());
        	if(userVO != null) {
                ncvo.setCreator(map.get(ncvo.getCreator()).getUser_name());
        	}
        }
      }
    } 
    WebFileParaConvertor convertor = new WebFileParaConvertor();
    WebFileParaVO[] ret = convertor.convert(ncList
        .toArray(new NCFileVO[0]), para.getBillId(), newBucket);
    
    for (int i = 0; ret != null && i < ret.length; i++) {
      String fullpath = filePathMap.get(ret[i].getPk());
      if (fullpath != null && !"".equals(fullpath)) {
        ret[i].setFullPath(fullpath);
      }
    } 
    
    if (!cibFileDocs.isEmpty()) {
      try {
        for (WebFileParaVO webFileParaVO : ret) {
          if (cibFileDocs.contains(webFileParaVO.getPk_doc())) {
            processSignFileReturnData(webFileParaVO);
          }
        } 
      } catch (BusinessException e) {
        ExceptionUtils.wrapException(e);
      } 
    }
    return ret;
  }










  
  @Deprecated
  protected String[] queryEbankEleReceipt(String billID) throws BusinessException {
    List<String> reList = new ArrayList<String>();
    return reList.toArray(new String[0]);
  }

  
  private String getStorePath(WebFileParaVO para) { return IFileStorageConst.Bucket; }








  
  protected NCFileVO[] queryBankReceiptFiles(String pk_busibill) throws BusinessException { return null; }








  
  protected WebFileParaVO[] processReturnData(WebFileParaVO[] retVOArr) throws BusinessException { return retVOArr; }










  
  protected NCFileVO[] querySignCIBFiles(String pk_busibill) throws BusinessException { return null; }
  
  protected void processSignFileReturnData(WebFileParaVO retVO) throws BusinessException {}
}
